package com.yx.cloud.activity;

import android.app.Dialog;
import android.content.res.Resources;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.NumberPicker;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;

import com.google.android.material.bottomsheet.BottomSheetDialog;
import com.google.gson.Gson;
import com.iot.base.service.req.RenameDeviceParam;
import com.iot.product.sweeper.bean.QuietHour;
import com.iot.product.sweeper.config.SweeperProductConfig;
import com.iot.sweeper.AppContext;
import com.iot.sweeper.param.CleanSettingParam;
import com.iot.sweeper.param.SetQuiteTimeParam;
import com.yx.cloud.MyApplication;
import com.yx.cloud.R;
import com.yx.cloud.base.BaseActivity;
import com.yx.cloud.constant.Constants;
import com.yx.cloud.databinding.RobotsettingsActivityBinding;
import com.yx.cloud.product.ProductConfigConstants;
import com.yx.cloud.utils.DisplayUtil;
import com.yx.cloud.utils.Intent_utils;
import com.yx.cloud.utils.LoadProgressDialog;
import com.yx.cloud.utils.RomUtils;
import com.yx.cloud.utils.ToastUtil;
import com.iot.product.sweeper.bean.CleanSettings;
import com.iot.product.sweeper.bean.Robot;
import com.iot.common.utils.Event;
import com.iot.common.utils.LogUtils;
import com.yx.cloud.view.TimeEntity;
import com.yx.cloud.view.TimeWheelLayout;

import java.lang.reflect.Field;
import java.util.List;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import static com.iot.common.utils.Event.MESSAGE_TYPE_ADD_NO_DISTURB;
import static com.iot.common.utils.Event.MESSAGE_TYPE_MODIFY_NO_DISTURB;
import static com.iot.common.utils.Event.MESSAGE_TYPE_SWITCH_NO_DISTURB;

public class RobotSettingsActivity extends BaseActivity implements View.OnClickListener {
    private final static String TAG = "RobotSettingsActivity";
    private CleanSettings settings;
    private Robot robot;
    private Dialog renamedialog, unitAredDialig;
    private EditText mEtName;
    private int startTime_hour;
    private int startTime_minute;
    private int endTime_hour;
    private int endTime_minute;
    private TimeWheelLayout timeWheelLayout;
    private LoadProgressDialog loadProgressDialog;
    private RobotsettingsActivityBinding binding;
    private int mUnitSettings;
    private QuietHour quietHour;

    @Override
    public void onCreate() {
        binding = RobotsettingsActivityBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        initData();
    }

    @Override
    protected void onStart() {
        super.onStart();
        AppContext.getProductService().getQuiteTimeSettings();
    }


    private void initData() {
        loadProgressDialog = new LoadProgressDialog(this);

        robot = AppContext.get().getCurrentDevice();
        if (robot == null) {
            return;
        }
        settings = robot.getCleanSettings();

        binding.rlEquipmentName.setVisibility(View.VISIBLE);
        binding.rlEquipmentMessage.setVisibility(View.VISIBLE);
        JSONObject productConfig = AppContext.getConfig();
        DisplayUtil.show(binding.rlVolumeAdjustment, productConfig.optBoolean(ProductConfigConstants.robotSetting_volume));
        DisplayUtil.show(binding.rlContinuousCleaning, productConfig.optBoolean(ProductConfigConstants.robotSetting_break_continue));
        DisplayUtil.show(binding.rlDisturbMode, productConfig.optBoolean(ProductConfigConstants.robotSetting_no_disturb));
        DisplayUtil.show(binding.rlSilentMode, productConfig.optBoolean(ProductConfigConstants.robotSetting_silent));
        DisplayUtil.show(binding.rlRestoreFactorySettings, productConfig.optBoolean(ProductConfigConstants.robotSetting_factoryset));
        DisplayUtil.show(binding.rlLight, productConfig.optBoolean(ProductConfigConstants.robotSetting_light));
        DisplayUtil.show(binding.rlFirmwareAutoUpdate, productConfig.optBoolean(ProductConfigConstants.hasFirmwareAutoUpdate));
        DisplayUtil.show(binding.rlUnitArea, productConfig.optBoolean(ProductConfigConstants.cleaning_unit_area));
        DisplayUtil.show(binding.rlChildLock, productConfig.optBoolean(ProductConfigConstants.child_lock));

        //修改后监听回调没有更改问题
        String deviceName = robot.getName();
        binding.tvDeviceName.setText(deviceName);
        LogUtils.i("机器人 名称 11111111111: " + deviceName);
        if (robot.isShare()) {
            binding.rlRestoreFactorySettings.setVisibility(View.GONE);
            //如果是分享的设备，就不显示自动更新按钮
            binding.rlFirmwareAutoUpdate.setVisibility(View.GONE);
        } else {
            //如果不是分享的设备
//            AppContext.getProductService().getAutoUpgradeSwitchState();//获取固件自动更新状态
        }

        quietHour = new QuietHour();
        List<QuietHour> quietHourList = robot.getQuietHourList();
        if (quietHourList.size() > 0) {
            QuietHour quietHour = quietHourList.get(0);
            int startHour = quietHour.getStartTime() / 3600;
            int startMin = quietHour.getStartTime() / 60 % 60;
            int endHour = quietHour.getEndTime() / 3600;
            int endMin = quietHour.getEndTime() / 60 % 60;
            setQuiteHourSwitch(quietHour.isEnable());
            showQuiteHour(startHour, startMin, endHour, endMin);
        } else {
            setQuiteHourSwitch(false);
            showQuiteHour(20, 0, 8, 0);
        }
        //单位面积
        if (productConfig.optBoolean(ProductConfigConstants.cleaning_unit_area)) {
            int unitSettings = settings.getUnitSettings();
            if (0 == unitSettings) {
                binding.tvSquareMeter.setText(getString(R.string.MO_Square_Meter));
            } else if (1 == unitSettings) {
                binding.tvSquareMeter.setText(getString(R.string.MO_Square_Foot));
            }
        }
        //勿扰模式
        binding.switchDisturb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!binding.switchDisturb.isPressed()) {
                    return;
                }
                loadProgressDialog.show();
                setQuiteHourSwitch(isChecked);
                sendQuiteHourSwitch();
            }
        });

        //断点续扫模式
        boolean breakpointResume = settings.isBreakpointResume();
        binding.remoteControlSwitchAutoBoost.setChecked(breakpointResume);
        binding.remoteControlSwitchAutoBoost.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (!binding.remoteControlSwitchAutoBoost.isPressed()) {
                    return;
                }
                loadProgressDialog.show();
                sendAutoBoost(isChecked);
            }
        });

        //静音模式
//        binding.remoteControlSwitchQuietMode.setChecked(settings.isQuietMode());
//        binding.remoteControlSwitchQuietMode.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                if (!binding.remoteControlSwitchQuietMode.isPressed()) {
//                    return;
//                }
////                HashMap<String, Object> hashMap = new HashMap<>();
////                hashMap.put("103", isChecked);
////                TuyaSdk.get().publishDps(JSONObject.toJSONString(hashMap));
//            }
//        });

        //估计自动更新
        binding.cbFirmwareAutoUpdate.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                AppContext.getProductService().setChangeAutoUpgradeSwitchState(isChecked ? 1 : 0);
            }
        });
        if (productConfig.optBoolean(ProductConfigConstants.robotSetting_light)) {
            boolean lightSwitch = settings.isLightSwitch();
            binding.cbLight.setChecked(lightSwitch);
            binding.cbLight.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                //灯光
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    AppContext.getProductService().setLightControls(isChecked);
                }
            });
        }
        //童锁
        if (productConfig.optBoolean(ProductConfigConstants.child_lock)) {
            binding.cbChildLockSwitch.setChecked(settings.isChildLock());
            binding.cbChildLockSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
                    AppContext.getProductService().setDeviceCleanSettings(CleanSettingParam.newBuilder().childLock(isChecked).build());
                }
            });
        }
        binding.ivGeneralSettingReturn.setOnClickListener(this);
        binding.rlEquipmentName.setOnClickListener(this);
        binding.rlVolumeAdjustment.setOnClickListener(this);
        binding.rlEquipmentMessage.setOnClickListener(this);
        binding.rlRestoreFactorySettings.setOnClickListener(this);
        binding.rlStartTime.setOnClickListener(this);
        binding.llEndTime.setOnClickListener(this);
        binding.rlUnitArea.setOnClickListener(this);

    }

    /**
     * 断点续扫
     *
     * @param isChecked
     */
    private void sendAutoBoost(boolean isChecked) {
        AppContext.getProductService().setDeviceCleanSettings(CleanSettingParam.newBuilder().breakpointResume(isChecked).build());
    }

    @Override
    public void onClick(View v) {
        if (RomUtils.isFastClick()) {
            return;
        }
        int id = v.getId();
        if (id == R.id.iv_generalSetting_return) {
            Intent_utils.backIntent(this);
        } else if (id == R.id.rl_equipment_Name) {
            setRobotNameDialog(1);
        } else if (id == R.id.rl_volume_Adjustment) {
            Intent_utils.enterIntent(this, VoiceVolumeSettingActivity.class);
        } else if (id == R.id.rl_equipmentMessage) {
            Intent_utils.enterIntent(this, EquipmentMessageActivity.class);
        } else if (id == R.id.rl_restoreFactorySettings) {
            //恢复出厂设置
            setRobotNameDialog(2);
        } else if (id == R.id.rl_startTime) {
            setTimeDialog("start", startTime_hour, startTime_minute);
        } else if (id == R.id.ll_endTime) {
            setTimeDialog("end", endTime_hour, endTime_minute);
        } else if (id == R.id.rl_unitArea) {
            //平方米
            setUnitAreaDialog();
        }
    }

    private void setUnitAreaDialog() {
        unitAredDialig = new Dialog(this);
        unitAredDialig.setContentView(R.layout.unit_ared_dialog);
        unitAredDialig.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        unitAredDialig.setCanceledOnTouchOutside(false);

        Window window = unitAredDialig.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.CENTER;

        TextView mBtnUnitAreaConfirm = unitAredDialig.findViewById(R.id.btn_unitAreaConfirm);
        TextView mBtnUnitAreaCancel = unitAredDialig.findViewById(R.id.btn_unitAreaCancel);
        //        Display display = this.getWindowManager().getDefaultDisplay();
//        LinearLayout ll_unitAredDialogLayout = unitAredDialig.findViewById(R.id.ll_unitAredDialogLayout);
//        ViewGroup.LayoutParams params = ll_unitAredDialogLayout.getLayoutParams();
//        params.width = (int) (display.getWidth() * 0.8);
//        ll_unitAredDialogLayout.setLayoutParams(params);

        RadioGroup rg_squareMeterAndSquareFeet = (RadioGroup) unitAredDialig.findViewById(R.id.rg_squareMeterAndSquareFeet);
        RadioButton rb_square_meter = unitAredDialig.findViewById(R.id.rb_square_meter);
        RadioButton rb_square_feet = unitAredDialig.findViewById(R.id.rb_square_feet);

        Robot device = AppContext.get().getCurrentDevice();
        if (device != null) {
            int unitSettings = device.getCleanSettings().getUnitSettings();
            LogUtils.i("单位面积 ：" + unitSettings);
            if (0 == unitSettings) {
                mUnitSettings = 0;
                rb_square_meter.setChecked(true);
            } else if (1 == unitSettings) {
                mUnitSettings = 1;
                rb_square_feet.setChecked(true);
            }
        }
        rg_squareMeterAndSquareFeet.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                if (rb_square_meter.isChecked()) {
                    LogUtils.i("选中 平方米");
                    mUnitSettings = 0;
                } else {
                    LogUtils.i("x 选中 平方米");
                }
                if (rb_square_feet.isChecked()) {
                    LogUtils.i("选中 平方英尺");
                    mUnitSettings = 1;
                } else {
                    LogUtils.i("x 选中 平方英尺");
                }
            }
        });
        mBtnUnitAreaConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                AppContext.getProductService().setDeviceCleanSettings(CleanSettingParam.newBuilder().setUnitSettings(mUnitSettings).build());
                unitAredDialig.dismiss();
            }
        });
        mBtnUnitAreaCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                unitAredDialig.dismiss();
            }
        });
        unitAredDialig.show();
    }

    /**
     * 设置机器人名字
     */
    private void setRobotNameDialog(final int type) {
        renamedialog = new Dialog(this);
        renamedialog.setContentView(R.layout.set_robotname_dialog);
        renamedialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        renamedialog.setCanceledOnTouchOutside(false);

        Window window = renamedialog.getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        params.width = WindowManager.LayoutParams.MATCH_PARENT;
        params.height = WindowManager.LayoutParams.WRAP_CONTENT;
        params.gravity = Gravity.CENTER;

        TextView mTvDialogTitle = renamedialog.findViewById(R.id.tv_dialogTitle);
        TextView mBtnRobotNameConfirm = renamedialog.findViewById(R.id.btn_robotNameConfirm);
        TextView mBtnRobotNameCancel = renamedialog.findViewById(R.id.btn_robotNameCancel);
        mEtName = renamedialog.findViewById(R.id.et_name);
        final TextView mfactorySettings = renamedialog.findViewById(R.id.tv_factorySettings);
        //显示出厂设置的Dialog界面
        if (type == 2) {
            mTvDialogTitle.setText(getString(R.string.MO_FactoryReset));
            mEtName.setVisibility(View.GONE);
            mfactorySettings.setVisibility(View.VISIBLE);
            mfactorySettings.setText(getString(R.string.factory_state));
        } else {
            //显示设备名称的Dialog界面
            mTvDialogTitle.setText(getString(R.string.U_RobotName));
            mEtName.setVisibility(View.VISIBLE);
            String mDeviceName = binding.tvDeviceName.getText().toString().trim();
            mEtName.setText(mDeviceName);
            mfactorySettings.setVisibility(View.GONE);
        }
        mBtnRobotNameConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                //显示出厂设置的Dialog界面
                if (type == 2) {
                    //恢复出厂设置接口
                    AppContext.getProductService().factoryReset();
                } else {
                    //显示设备名称的Dialog界面
                    String deviceNewName = mEtName.getText().toString().trim();
                    if (!TextUtils.isEmpty(deviceNewName)) {
                        binding.tvDeviceName.setText(deviceNewName);
                        Constants.newRobotName = deviceNewName;
                        RenameDeviceParam param = new RenameDeviceParam();
                        param.setName(deviceNewName);
                        AppContext.getProductService().renameDevice(param);
                        renamedialog.dismiss();
                    } else {
                        ToastUtil.show(RobotSettingsActivity.this, getString(R.string.U_RobotName_Hint), Toast.LENGTH_SHORT);
                    }
                }
            }
        });
        mBtnRobotNameCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                renamedialog.dismiss();
            }
        });
        renamedialog.show();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(Event event) {
        switch (event.getType()) {
            case Event.MESSAGE_TYPE_CHILD_LOCK:
                //童锁
                boolean childLock = settings.isChildLock();//童锁
                binding.cbChildLockSwitch.setChecked(childLock);
                break;
            case Event.MESSAGE_TYPE_UNIT_AREA:
                //单位面积
                int unitSettings = settings.getUnitSettings();//单位面积
                if (0 == unitSettings) {
                    binding.tvSquareMeter.setText(getString(R.string.MO_Square_Meter));
                } else if (1 == unitSettings) {
                    binding.tvSquareMeter.setText(getString(R.string.MO_Square_Foot));
                }
                break;
            case Event.MESSAGE_TYPE_RESTORE_FACTORY:
                //恢复出厂设置
                if (event.isResult()) {
                    Intent_utils.enterIntent(this, MainActivity2.class);
                    finish();
                } else {
                    ToastUtil.show(this, event.getContent().toString(), Toast.LENGTH_LONG);
                    return;
                }
                break;
            case Event.MESSAGE_TYPE_RENAME_DEVICE:
                //修改设备名称
                if (event.isResult()) {
                    binding.tvDeviceName.setText(Constants.newRobotName);
                    Event.newBuilder().type(Event.MESSAGE_TYPE_DEVICE_INFO_UPDATE).result(true).content(Constants.newRobotName).send();
                } else {
                    ToastUtil.show(this, getString(R.string.U_T_RobotName_Edit_No), Toast.LENGTH_SHORT);
                }
                break;
            case Event.MESSAGE_TYPE_DEVICE_INFO_UPDATE:
                //修改设备名后回调
                if (event.isResult()) {
//                    Constants.isRight_deleteRobot_updateName = true;
                    Robot device = (Robot) event.getContent();
                    robot.setName(device.getName());
                    Constants.newRobotName = device.getName();
                    binding.tvDeviceName.setText(Constants.newRobotName);
                    LogUtils.d("controlDevice onDevInfoUpdat: " + device.getName());
                }
                break;
            case Event.MESSAGE_TYPE_GET_NO_DISTURB:
                if (loadProgressDialog != null && loadProgressDialog.isShowing()) {
                    loadProgressDialog.dismiss();
                }
                List<QuietHour> quietHourtList = robot.getQuietHourList();
                Log.i(TAG, "勿扰 上报 ---------------------" + quietHourtList.size());
                if (quietHourtList != null && quietHourtList.size() > 0) {
                    quietHour = quietHourtList.get(0);
                    int startHour = quietHour.getStartTime() / 3600;
                    int startMin = quietHour.getStartTime() / 60 % 60;
                    int endHour = quietHour.getEndTime() / 3600;
                    int endMin = quietHour.getEndTime() / 60 % 60;

                    setQuiteHourSwitch(quietHour.isEnable());
                    showQuiteHour(startHour, startMin, endHour, endMin);
                   /* for(QuietHour quietHour1 : quietHourtList){
                        AppContext.getProductService().deleteNoDisturb(quietHour1.getUndisturbedId());
                    }*/
                }
                break;
            case MESSAGE_TYPE_ADD_NO_DISTURB:      //添加勿扰
            case MESSAGE_TYPE_SWITCH_NO_DISTURB:      //开关勿扰
            case MESSAGE_TYPE_MODIFY_NO_DISTURB:   //修改勿扰
                AppContext.getProductService().getQuiteTimeSettings();
                break;
            case Event.MESSAGE_TYPE_AUTO_UPGRADE_SWITCH_STATE:
                //固件自动更新状态
                if (event.isResult()) {
                    int autoUpgradeSwitchState = (int) event.getContent();
                    Log.i(TAG, "固件自动更新状态 11111111111111111111111: :" + autoUpgradeSwitchState);
                    if (autoUpgradeSwitchState == 1) {
                        binding.cbFirmwareAutoUpdate.setChecked(true);
                    } else if (autoUpgradeSwitchState == 0) {
                        binding.cbFirmwareAutoUpdate.setChecked(false);
                    }
                } else {
                    Log.i(TAG, "固件自动更新状态 2222222: :" + event.getContent().toString());
                }
                break;
            case Event.MESSAGE_TYPE_BREAKPOINT_RESUME_SWITCH:
                //断点续扫开关
                loadProgressDialog.dismiss();
                break;
        }
    }


    /**
     * 底部弹框
     */
    @RequiresApi(api = Build.VERSION_CODES.M)
    private void setTimeDialog(String timeSign, int timeHour, int timeMin) {

        BottomSheetDialog sheetDialog = new BottomSheetDialog(RobotSettingsActivity.this);
        View view = LayoutInflater.from(this).inflate(R.layout.time_bottomsheet_dialog, null);

        timeWheelLayout = view.findViewById(R.id.timeWheel_DialogLayout);
        TextView mTvTimeCancel = view.findViewById(R.id.tv_timeCancel);
        TextView mTvTimeConfirm = view.findViewById(R.id.tv_timeConfirm);
//        setNumberPickerDivider();
        if ("start".equals(timeSign)) {
            startTime_hour = timeHour;
            startTime_minute = timeMin;
            timeWheelLayout.setDefaultValue(TimeEntity.target(timeHour, timeMin, 00));
        } else {
            endTime_hour = timeHour;
            endTime_minute = timeMin;
            timeWheelLayout.setDefaultValue(TimeEntity.target(timeHour, timeMin, 00));
        }

        mTvTimeCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sheetDialog.dismiss();
            }
        });
        mTvTimeConfirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (RomUtils.isFastClick()) {
                    return;
                }
                if ("start".equals(timeSign)) {
                    startTime_hour = timeWheelLayout.getSelectedHour();
                    startTime_minute = timeWheelLayout.getSelectedMinute();
                } else {
                    endTime_hour = timeWheelLayout.getSelectedHour();
                    endTime_minute = timeWheelLayout.getSelectedMinute();
                }

                showQuiteHour(startTime_hour, startTime_minute, endTime_hour, endTime_minute);
                sendQuiteHour();
                sheetDialog.dismiss();
            }
        });

        sheetDialog.setContentView(view);
        //设置透明背景
        sheetDialog.getWindow().findViewById(R.id.design_bottom_sheet)
                .setBackgroundResource(android.R.color.transparent);
        sheetDialog.show();
    }

    /**
     * TimePicker分割线的颜色和高度
     */
//    private void setNumberPickerDivider() {
//        Resources systemResources = Resources.getSystem();
//        int hourNumberPickerId = systemResources.getIdentifier("hour", "id", "android");
//        int minuteNumberPickerId = systemResources.getIdentifier("minute", "id", "android");
//        NumberPicker hourNumberPicker = (NumberPicker) tpTimePicker.findViewById(hourNumberPickerId);
//        NumberPicker minuteNumberPicker = (NumberPicker) tpTimePicker.findViewById(minuteNumberPickerId);
//        Field[] pickerFields = NumberPicker.class.getDeclaredFields();
//        for (Field pf : pickerFields) {
//            if (pf.getName().equals("mSelectionDivider")) {  //设置颜色
//                pf.setAccessible(true);
//                ColorDrawable colorDrawable = new ColorDrawable(
//                        ContextCompat.getColor(this, R.color.button_color2)); //选择自己喜欢的颜色
//                try {
//                    pf.set(hourNumberPicker, colorDrawable);
//                    pf.set(minuteNumberPicker, colorDrawable);
//                } catch (IllegalAccessException e) {
//                    e.printStackTrace();
//                }
//            }
//            if (pf.getName().equals("mSelectionDividerHeight")) {   //设置高度
//                pf.setAccessible(true);
//                try {
//                    int result = 5;  //要设置的高度
//                    pf.set(hourNumberPicker, result);
//                    pf.set(minuteNumberPicker, result);
//                } catch (Exception e) {
//                    e.printStackTrace();
//                }
//                break;
//            }
//            hourNumberPicker.invalidate();
//            minuteNumberPicker.invalidate();
//        }
//    }
    private void sendQuiteHour() {
        String startTimeHou = binding.tvStartTimeHour.getText().toString().trim();
        String startTimeMinute = binding.tvStartTimeMinute.getText().toString().trim();
        String endTimeHou = binding.tvEndTimeHour.getText().toString().trim();
        String endTimeMinute = binding.tvEndTimeMinute.getText().toString().trim();

        try {
            SetQuiteTimeParam setQuiteTimeParam = SetQuiteTimeParam.newBuilder().setTime(
                    Integer.parseInt(startTimeHou),
                    Integer.parseInt(startTimeMinute),
                    Integer.parseInt(endTimeHou),
                    Integer.parseInt(endTimeMinute)
            ).setSwitch(true).build();
            setQuiteTimeParam.setRepeat(quietHour.getRepeat());
            setQuiteTimeParam.setUndisturbedId(quietHour.getUndisturbedId());
            setQuiteTimeParam.setStartCondId(quietHour.getStartCondId());
            setQuiteTimeParam.setEndCondId(quietHour.getEndCondId());
            setQuiteTimeParam.setHasDisturbed(true);
            setQuiteTimeParam.setHasSetTime(true);
            setQuiteTimeParam.setHasSetSwitch(false);
            LogUtils.i("勿扰数据 ：" + new Gson().toJson(setQuiteTimeParam));
            AppContext.getProductService().setQuiteTimeSettings(setQuiteTimeParam);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    private void sendQuiteHourSwitch() {
        SetQuiteTimeParam setQuiteTimeParam = SetQuiteTimeParam.newBuilder().setSwitch(binding.switchDisturb.isChecked()).build();
        setQuiteTimeParam.setHasSetTime(false);
        setQuiteTimeParam.setHasSetSwitch(true);
        if (robot.getQuietHourList() != null && robot.getQuietHourList().size() > 0) {
            setQuiteTimeParam.setStartHour(quietHour.getStartTime() / 3600);
            setQuiteTimeParam.setStartMin((quietHour.getStartTime() % 3600) / 60);
            setQuiteTimeParam.setUndisturbedId(quietHour.getUndisturbedId());
            setQuiteTimeParam.setHasDisturbed(true);
        } else {
            setQuiteTimeParam.setHasDisturbed(false);
            setQuiteTimeParam.setStartHour(22);
            setQuiteTimeParam.setStartMin(0);
            setQuiteTimeParam.setEndHour(8);
            setQuiteTimeParam.setEndMin(0);
        }
        AppContext.getProductService().setQuiteTimeSettings(setQuiteTimeParam);
    }

    private void showQuiteHour(int startHour, int startMin, int endHour, int endMin) {
        startTime_hour = startHour;
        startTime_minute = startMin;
        endTime_hour = endHour;
        endTime_minute = endMin;

        setTime(binding.tvStartTimeHour, startHour);
        setTime(binding.tvStartTimeMinute, startMin);
        setTime(binding.tvEndTimeHour, endHour);
        setTime(binding.tvEndTimeMinute, endMin);
        int startTime = startHour * 60 + startMin;
        int endTime = endHour * 60 + endMin;
        if (startTime > endTime) {
            binding.tvDataSign.setVisibility(View.VISIBLE);
        } else {
            binding.tvDataSign.setVisibility(View.GONE);
        }
    }

    private void setQuiteHourSwitch(boolean isActive) {
        if (isActive) {
            binding.switchDisturb.setChecked(true);
            binding.rlStartTime.setVisibility(View.VISIBLE);
            binding.llEndTime.setVisibility(View.VISIBLE);
            binding.robotSetingView.setVisibility(View.VISIBLE);
            binding.robotSetingView2.setVisibility(View.VISIBLE);
        } else {
            binding.switchDisturb.setChecked(false);
            binding.rlStartTime.setVisibility(View.GONE);
            binding.llEndTime.setVisibility(View.GONE);
            binding.robotSetingView.setVisibility(View.GONE);
            binding.robotSetingView2.setVisibility(View.GONE);
        }
    }

    private void setTime(TextView tv, int time) {
        tv.setText(time < 10 ? "0" + time : "" + time);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }
}
